package leetcode.code0473;

import java.util.Arrays;

import leetcode.IDebug;
import leetcode.helper.HelpDebug;

//
public class Solution2 implements IDebug {

	public boolean makesquare(int[] matchsticks) {
		int total = 0;
		for (int num : matchsticks) {
			total += num;
		}
		if (total % 4 != 0) {
			return false;
		}
		int aim = total / 4;
		Arrays.sort(matchsticks);
		int len = matchsticks.length;
		int l = 0, r = len - 1;
		int cur = 0;
		int find = 4;
		while (l <= r) {
			if (l == r) {
				cur += matchsticks[l];
				l++;
			} else if (cur + matchsticks[r] <= aim) {
				cur += matchsticks[r];
				r--;
			} else {
				cur += matchsticks[l];
				l++;
			}
			if (cur == aim) {
				cur = 0;
				find--;
			}
		}
		return find == 0 && cur == 0;
	}

	@Override
	public void debug1() {
		HelpDebug.compare(true, this.makesquare(HelpDebug.str2array3("[5,5,5,5,4,4,4,4,3,3,3,3]")));

	}

	@Override
	public void debug2() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug3() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug4() {
		// TODO Auto-generated method stub

	}

	public static void main(String[] args) {
		Solution2 so = new Solution2();
		so.debug1();
		so.debug2();
		so.debug3();
		so.debug4();

	}

}
